package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.TokenConstants;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.enums.HelpEnums;
import com.ytjj.qmyx.mall.enums.HelpInfoEnums;
import com.ytjj.qmyx.mall.mapper.HelpWorkInfoDao;
import com.ytjj.qmyx.mall.mapper.HelpWorkInfoMapper;
import com.ytjj.qmyx.mall.mapper.UserHelpWorkDetailMapper;
import com.ytjj.qmyx.mall.model.HelpWorkInfo;
import com.ytjj.qmyx.mall.model.HelpWorkInfoExample;
import com.ytjj.qmyx.mall.model.UserHelpWorkDetail;
import com.ytjj.qmyx.mall.model.UserHelpWorkDetailExample;
import com.ytjj.qmyx.mall.model.dto.HelpWorkInfoDto;
import com.ytjj.qmyx.mall.model.dto.UserHelpWorkDetailDto;
import com.ytjj.qmyx.mall.service.HelpWorkInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 
 * @description:
 */
@Service
@Slf4j
@RefreshScope
public class HelpWorkInfoServiceImpl implements HelpWorkInfoService {

    @Autowired
    HelpWorkInfoMapper helpWorkInfoMapper;

    @Autowired
    UserHelpWorkDetailMapper userHelpWorkDetailMapper;

    @Autowired
    HelpWorkInfoDao helpWorkInfoDao;

    @Autowired
    RedisService redisService;

    @Value("${qmyx.helpWorkInfo.helpNum:13}")
    private int helpNum;


    @Override
    public HelpWorkInfoDto getInfoList() {
        //1.当前用户是否登录
        UsersResponse usersResponse = this.getCurrentUserInfo();
        //2.查询助力数据
        HelpWorkInfoExample helpWorkInfoExample = new HelpWorkInfoExample();
        helpWorkInfoExample.createCriteria().andUserIdEqualTo(usersResponse.getId());
        long count = helpWorkInfoMapper.countByExample(helpWorkInfoExample);
        if(count == 0){
            //3.没有数据则创建助力单
            HelpWorkInfo helpWorkInfo = new HelpWorkInfo();
            //设置助力人数，一旦助力单创建，助力人数就确定了，helpNum修改也不影响当前的助力单的人数
            helpWorkInfo.setHelpNum(helpNum);
            helpWorkInfo.setHelpNumKo(0);
            helpWorkInfo.setIsFinished(0);
            helpWorkInfo.setProductType(HelpInfoEnums.HELP_PRODUCT_TYPE.getCode());
            helpWorkInfo.setUserId(usersResponse.getId());
            helpWorkInfoMapper.insertSelective(helpWorkInfo);
        }

        HelpWorkInfoDto infoList = helpWorkInfoDao.getInfoList(usersResponse.getId());
        if(infoList == null){
            throw new ApiException("操作频繁，请重试");
        }
        //3.赋值助力用户列表
        List<UserHelpWorkDetailDto> userHelpWorkDetailDtos = helpWorkInfoDao.getDetails(infoList.getId());
        infoList.setUserHelpWorkDetailDtos(userHelpWorkDetailDtos);
        return infoList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String,Object> helpThem(Integer helpWorkId) {
        if(helpWorkId == null){
            throw new ApiException("助力单不存在");
        }
        Map<String,Object> map = new HashMap<>();
        //1.当前用户是否登录
        UsersResponse usersResponse = this.getCurrentUserInfo();
        HelpWorkInfo helpWorkInfo = helpWorkInfoMapper.selectByPrimaryKey(helpWorkId);

        if(helpWorkInfo == null){
            throw new ApiException("助力单不存在");
        }
        //2.是否是本人
        if(helpWorkInfo.getUserId().equals(usersResponse.getId())){
            map.put("code", HelpEnums.ONESELF_NO_HELP.getCode());
            map.put("result",HelpEnums.ONESELF_NO_HELP.getMessage());
            return map;
        }

        //3.当前用户是否已助力
        UserHelpWorkDetailExample userHelpWorkDetailExample = new UserHelpWorkDetailExample();
        userHelpWorkDetailExample.createCriteria().andUserIdEqualTo(usersResponse.getId()).andHelpWorkIdEqualTo(helpWorkId);
        long count = userHelpWorkDetailMapper.countByExample(userHelpWorkDetailExample);
        if(count > 0){
            map.put("code", HelpEnums.ALREADY_HELP.getCode());
            map.put("result",HelpEnums.ALREADY_HELP.getMessage());
            return map;
        }

        //4.判断助力是否完成
        if(helpWorkInfo.getHelpNumKo() >= helpWorkInfo.getHelpNum() || helpWorkInfo.getIsFinished() == 1){
            map.put("code", HelpEnums.HELP_FRIEND_FINISH.getCode());
            map.put("result",HelpEnums.HELP_FRIEND_FINISH.getMessage());
        }else{
            UserHelpWorkDetail userHelpWorkDetail = new UserHelpWorkDetail();
            userHelpWorkDetail.setHelpWorkId(helpWorkId);
            userHelpWorkDetail.setUserId(usersResponse.getId());
            userHelpWorkDetailMapper.insertSelective(userHelpWorkDetail);
            //5.判断助力是否完成
            Integer result = helpWorkInfoDao.incHelpcount(helpWorkId);
            //5.1设置助力结果
            map.put("result", result > 0 ? HelpEnums.HELP_SUCCEED.getMessage() : HelpEnums.HELP_FRIEND_FINISH.getMessage());
            map.put("code", result > 0 ? HelpEnums.HELP_SUCCEED.getCode() : HelpEnums.HELP_FRIEND_FINISH.getMessage());
            //5.2助力是否完成
            HelpWorkInfo newHelpWorkInfo = helpWorkInfoMapper.selectByPrimaryKey(helpWorkId);
            if(newHelpWorkInfo.getHelpNumKo() >= helpWorkInfo.getHelpNum()){
                HelpWorkInfo helpWorkInfo1 = new HelpWorkInfo();
                helpWorkInfo1.setId(helpWorkId);
                helpWorkInfo1.setIsFinished(1);
                helpWorkInfoMapper.updateByPrimaryKeySelective(helpWorkInfo1);
                map.put("code", HelpEnums.HELP_SUCCEED.getCode());
            }
        }
        return map;
    }

    /**
    * 获得当前登录用户的信息
    * @returns: com.ytjj.common.model.UsersResponse
    * 
    */
    public UsersResponse getCurrentUserInfo(){
        String token = TokenUtil.getToken();
        if(StringUtil.isEmpty(token)){
            throw new ApiException(ResultCode.UNAUTHORIZED);
        }
        String usesInfo = redisService.get(token);
        if (StringUtil.isEmpty(usesInfo)) {
            throw new ApiException(ResultCode.UNAUTHORIZED);
        }
        redisService.expire(token, TokenConstants.EXPIRE_SECONDS);
        UsersResponse usersResponse = JSONObject.parseObject(usesInfo,UsersResponse.class);
        return usersResponse;
    }
}
